package com.vitalfit.service.serviceImpl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vitalfit.exception.UserAlreadyExistsException;
import com.vitalfit.exception.UserNotFoundException;
import com.vitalfit.exception.WrongPasswordException;
import com.vitalfit.mapper.CustomerMapper;
import com.vitalfit.model.dto.LoginCustomerDTO;
import com.vitalfit.model.dto.RegisterCustomerDTO;
import com.vitalfit.model.entity.user.Customer;
import com.vitalfit.model.entity.user.ShopManager;
import com.vitalfit.model.entity.user.User;
import com.vitalfit.model.vo.LoginCustomerVO;
import com.vitalfit.model.vo.RegisterCustomerVO;
import com.vitalfit.repository.UserRepository;
import com.vitalfit.service.AuthService;
import com.vitalfit.utils.TokenUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final UserRepository userRepository;


    private final PasswordEncoder passwordEncoder;



    @Transactional
    @Override
    public RegisterCustomerVO registerCustomer(RegisterCustomerDTO registerCustomerDTO){

        if (userRepository.existsByEmail(registerCustomerDTO.getEmail())) {
            throw new UserAlreadyExistsException("User with email: " + registerCustomerDTO.getEmail() + " already exists");
        }
        Customer customer = new Customer();
        customer.setEmail(registerCustomerDTO.getEmail());
        customer.setName(registerCustomerDTO.getName());
        customer.setPassword(passwordEncoder.encode(registerCustomerDTO.getPassword()));
        userRepository.save(customer);
        return CustomerMapper.INSTANCE.customerToRegisterCustomerVO(customer);
    }

    @Override
    @Transactional
    public LoginCustomerVO loginCustomer(LoginCustomerDTO loginCustomerDTO) {

        User user = userRepository.findByEmail(loginCustomerDTO.getEmail());

        // 检查用户是否存在
        if (user == null) {
            throw new UserNotFoundException("User not found with the given email");
        }

        // 验证密码
        boolean isPasswordMatching = passwordEncoder.matches(loginCustomerDTO.getPassword(), user.getPassword());
        if (!isPasswordMatching) {
            throw new WrongPasswordException("Incorrect password");
        }

        // 生成token
        JSONObject tokenJSONObject = new JSONObject();
        tokenJSONObject.put("id", user.getId());
        String token = TokenUtil.generateToken(JSON.toJSONString(tokenJSONObject));
        user.setToken(token);
        userRepository.save(user);

        return CustomerMapper.INSTANCE.customerToLoginCustomerVO((Customer) user);
    }


    @Transactional
    @Override
    public RegisterCustomerVO registerAdmin(RegisterCustomerDTO registerCustomerDTO){

        if (userRepository.existsByEmail(registerCustomerDTO.getEmail())) {
            throw new UserAlreadyExistsException("User with email: " + registerCustomerDTO.getEmail() + " already exists");
        }
        ShopManager shopManager = new ShopManager();
        shopManager.setEmail(registerCustomerDTO.getEmail());
        shopManager.setName(registerCustomerDTO.getName());
        shopManager.setPassword(passwordEncoder.encode(registerCustomerDTO.getPassword()));
        userRepository.save(shopManager);
        RegisterCustomerVO customerVO = new RegisterCustomerVO();
        customerVO.setName(registerCustomerDTO.getName());
        customerVO.setEmail(registerCustomerDTO.getEmail());
        return customerVO;


    }

    @Override
    @Transactional
    public LoginCustomerVO loginAdmin(LoginCustomerDTO loginCustomerDTO) {

        User user = userRepository.findByEmail(loginCustomerDTO.getEmail());

        // 检查用户是否存在
        if (user == null || user.getClass() != ShopManager.class) {
            throw new UserNotFoundException("User not found with the given email");
        }

        // 验证密码
        boolean isPasswordMatching = passwordEncoder.matches(loginCustomerDTO.getPassword(), user.getPassword());
        if (!isPasswordMatching) {
            throw new WrongPasswordException("Incorrect password");
        }

        // 生成token
        JSONObject tokenJSONObject = new JSONObject();
        tokenJSONObject.put("id", user.getId());
        String token = TokenUtil.generateToken(JSON.toJSONString(tokenJSONObject));
        user.setToken(token);
        userRepository.save(user);

        LoginCustomerVO loginCustomerVO = new LoginCustomerVO();
        loginCustomerVO.setToken(user.getToken());
        return loginCustomerVO;
    }

    @Transactional
    @Override
    public List<User> getAllUser(int page, int size){

        return userRepository.findAll();

    }


}

